package com.example.myapplication;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

import java.io.File;

public class VideoActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {

    private TextureView textureView;
    private Button playButton;
    MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        textureView = findViewById(R.id.textureView2);
        playButton = findViewById(R.id.btn_play);
    }

    public void btn_play(View view) {
        CharSequence text = playButton.getText();
        if (text.equals("开始播放")) {
            playButton.setText("停止播放");
            mediaPlayer = new MediaPlayer();   //非常注意这个的位置！！
            //设置准备完成的监听
            mediaPlayer.setOnPreparedListener(this);
            //设置完成时的监听
            mediaPlayer.setOnCompletionListener(this);

            //获取时间
            int duration = mediaPlayer.getDuration();
            int currentPosition = mediaPlayer.getCurrentPosition();

            try {
                //指定视频源
                mediaPlayer.setDataSource(new File(getExternalFilesDir(""), "a.mp4").getAbsolutePath());
            } catch (Exception e) {
                e.printStackTrace();
            }
            mediaPlayer.setSurface(new Surface(textureView.getSurfaceTexture()));
            //一般用异步
            mediaPlayer.prepareAsync();
        } else {
            playButton.setText("开始播放");
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mediaPlayer.start();  //准备好了才能开始
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        playButton.setText("开始播放");
        mediaPlayer.release();
    }


}